<template>
    <a-card :bordered="false">
        <div class="table-page-search-wrapper">
            <div class="title">多人码设置</div>
            <a-form-model ref="form1" :model="model" :rules="validatorRules">
                <a-form-model-item label="备注：" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                    <a-input v-model="model.remark" />
                </a-form-model-item>
                <a-form-model-item label=""  prop="" style="margin-left: 310px;"  :wrapperCol="wrapperCol">
                      <a-radio-group v-model="radioValue" @change="radioValueChange">
                        <a-radio :value="1">
                        部门
                        </a-radio>
                        <a-radio  :value="2">
                        人员名称
                        </a-radio>
                    </a-radio-group>
                     <a-input v-model="memberName" v-if="radioValue == 2" @change="memberchange" style="width: 1081px;" />
                    <el-cascader ref="cascade" :options="options" :props="optionProps" clearable filterable
                        :show-all-levels="false" @change="checkboxChange" v-model="treeObject" style="width: 1081px;" v-if="radioValue == 1"></el-cascader>
                </a-form-model-item>
                <a-form-model-item label="选中人员：" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="selectDiv">
                    <div class="selectDiv">
                        <span v-for="item in selectList" class="selectName">
                            <span>{{ item.name }}</span>
                            <a-icon type="close-circle" class="close" @click="delectSelect(item)" />
                        </span>
                    </div>
                </a-form-model-item>
                <a-form-model-item label="人员列表：" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="">
                    <div class="perpleSelect">
                        <a-checkbox @change="onChange" v-model="xuanzhong">全选</a-checkbox>
                        <div v-for=" item in renyuanList">
                            <!-- <div>当前部门:<span class="bumen">{{ item.name }}</span></div> -->
                            <div v-for=" (item1, index) in item.userList" :key="index" style="margin-left:20px;">
                                <div style="color:#f2954a;" >{{item1.deptFullName == '' || item1.deptFullName == undefined?'' :`部门：${item1.deptFullName}`}}</div>
                                <div @click="select(item1, item.id)" v-if="item1.isCheck" class="selectpre">{{
                                        item1.name
                                }}</div>
                                <div @click="select(item1, item.id)" v-else>{{ item1.name }}</div>
                            </div>
                        </div>
                    </div>

                </a-form-model-item>

                <div style="text-align:center;">
                    <a-button @click="cencal">
                        取消
                    </a-button>
                    <a-button type="primary" style="margin-left: 10px;" @click="onSubmit">
                        保存
                    </a-button>
                </div>
            </a-form-model>

        </div>
    </a-card>


</template>
<script>
import { saveOrUpdateCrowd, getCrowdVoById, departmentTree, getMemberListByDepId,memberListByName } from '@/api/marketingCenter/code';
import { stat } from 'fs';
import { CLIENT_RENEG_WINDOW } from 'tls';
export default {
    data() {
        var selectDiv = (rules, value, callback) => {
            if (this.selectList != undefined && this.selectList.length !== 0) {
                return callback()
            } else {
                callback("请添加人员!");
            }
        }
        return {
            xuanzhong:false,//全选
            treeList: [],
            treeObject: [],//树形绑定的数据
            optionProps: {
                value: 'id',
                label: 'name',
                children: 'children',
                // multiple: true,//多选
                multiple: false,//单选
                checkStrictly: true,
                emitPath: false//绑定的内容只获取最后一级的value值。
            },
            options: [],//树形数据
            bumenSelect: [],
            selectper: {},//当前选中人员的信息
            isCheck: false,//是否选中人员
            newArr: [],//定义一个新数组
            selectList: [],//选中人员
            renyuanList: [],//人员列表
            perple: [],
            tree: [],
            model: {},//页面数据
            labelCol: { span: 4 },
            wrapperCol: { span: 14 },
            validatorRules: {
                remark: [{ required: true, message: '请输入!' }],
                selectDiv: [{ validator: selectDiv, required: true, message: '请添加人员!' }],
            },
            drcodeId: '',//url上的id
            remark: '',
            form: this.$form.createForm(this, { name: 'form' }),
            open: true,
            radioValue:1,
            memberName:'',
            // end
            // labelCol: { span: 4 },
            // wrapperCol: { span: 14 },
        }
    },
    created() {
        var url = window.location.pathname.split('=')
        this.drcodeId = Number(url[1])
        if (this.drcodeId == 0 || this.drcodeId) {
            this.drcodeSet(this.drcodeId)
        }
        // 获取下拉框数据
        this.getTreeData()
    },
    methods: {
        //人员列表全选
        onChange() {
            var setlist={}
            if (this.renyuanList.length == 0) return
            this.renyuanList[0].userList.forEach(el=>{
                if(this.xuanzhong){//如果选中全选
                    el.isCheck=true
                    setlist={deptId: el.deptId, isCheck: true, name: el.name, userId: el.userId, id: el.id}
                    this.selectList.push(setlist)//把加载出来的人员列表全部改成选中状态
                    this.filterTransFer(this.selectList)
                }else{//如果不选中
                    el.isCheck=false
                    for (let index = 0; index < this.selectList.length; index++) {
                        const element = this.selectList[index];
                        if(el.id==element.id){//循环选中列表 如果id一样
                            this.selectList.splice(index, 1)//在选中人员中删除人员
                        }
                    }
                }
            })
        },
        getMemberListByName(e) {
            console.log(e);
            // memberListByName({name:this.memberName}).then(res => {
            //     console.log(res,'res-');
            // })
            this.$nextTick(() => {
            var aa = [];
                memberListByName({ name: this.memberName }).then(res => {
                    var flag = true;
                    for(let i=0,len=res.data.length;i<len;i++){
                        res.data[i].isCheck = false//设置默认未选中
                        if (this.selectList.length != 0) {//如果选中的人员不为空
                            this.selectList.forEach(e => {
                                if (e.name == res.data[i].name) {//如果选中的人员和接口返回的人员是一个则选中
                                    res.data[i].isCheck = true
                                }
                            })
                        }
                        if(res.data[i].isCheck==false){//如果有一个为false
                            flag = false;//则为false
                        }
                    }
                    if(flag){//如果全部选中
                        this.xuanzhong=true//则选中
                    }else{
                        this.xuanzhong=false//否则为fasle
                    }
                    this.perple = res.data
                    // aa.push({ name: item.name, id: xuanzhongID, userList: this.perple })
                    aa.push({ id: e, userList: this.perple })
                    this.renyuanList = aa//人员列表
                })
            })
        },
        memberchange() {
            this.getMemberListByName()
        },
        radioValueChange() {
            this.selectList = []
            this.renyuanList = []
            this.treeObject= {}
            this.memberName= ''
            this.xuanzhong = false
        },
        //获取详情
        drcodeSet(jhcodeId) {
            getCrowdVoById({ id: jhcodeId }).then(res => {
                this.model = res.data
                this.selectList = res.data.memberList
                res.data.memberList.forEach(e => {
                    this.bumenSelect.push(e.deptId);
                })
                // this.treeObject = this.bumenSelect//渲染部门
            })
        },
        //取消页面
        cencal() {
            this.$router.push(`/marketingCenter/code/jhcode/drcode`)
        },
        //保存
        onSubmit() {
            var push = {
                memberList: this.selectList,
                remark: this.model.remark
            }
            if (this.drcodeId == 0 || this.drcodeId) {
                push.id = this.drcodeId
            }
            this.$refs.form1.validate(valid => {
                if (valid && this.open == true) {
                    this.open = false
                    saveOrUpdateCrowd(push).then(res => {
                        this.open = true
                        if (res.success) {
                            this.$router.push(`/marketingCenter/code/jhcode/drcode`)
                        } else {
                            this.$message.warning(res.msg)
                        }
                    })
                }
            })
        },
        //获取树形
        getTreeData() {
            departmentTree().then(res => {
                this.options = res.data
            })
        },
        //树形的change
        checkboxChange(e) {
            this.$nextTick(() => {
            var aa = [];
                getMemberListByDepId({ deptId: e }).then(res => {
                    var flag = true;
                    for(let i=0,len=res.data.length;i<len;i++){
                        res.data[i].isCheck = false//设置默认未选中
                        if (this.selectList.length != 0) {//如果选中的人员不为空
                            this.selectList.forEach(e => {
                                if (e.name == res.data[i].name) {//如果选中的人员和接口返回的人员是一个则选中
                                    res.data[i].isCheck = true
                                }
                            })
                        }
                        if(res.data[i].isCheck==false){//如果有一个为false
                            flag = false;//则为false
                        }
                    }
                    if(flag){//如果全部选中
                        this.xuanzhong=true//则选中
                    }else{
                        this.xuanzhong=false//否则为fasle
                    }
                    this.perple = res.data
                    // aa.push({ name: item.name, id: xuanzhongID, userList: this.perple })
                    aa.push({ id: e, userList: this.perple })
                    this.renyuanList = aa//人员列表
                })
            })
            
        },
        //删除数组选中的人员
        delectSelect(item) {
            for (let index = 0; index < this.selectList.length; index++) {
                if (item.id == this.selectList[index].id) {//如果点击的是数组里面对应的id则删除
                    this.selectList[index].isCheck = false
                    //更改人员列表选中未选中
                    this.renyuanList.forEach(e => {//循环人员列表
                        e.userList.forEach(el => {
                            if (this.selectList[index].name == el.name) {//如果名字是一个则选中
                                el.isCheck = false
                            }
                        })
                        var flag = true;
                        for (let index = 0; index < e.userList.length; index++) {
                            const element = e.userList[index];
                            if(element.isCheck == false){//如果有一个为false
                                flag = false;//则为false
                            }
                        }
                        if(flag){//如果全部选中
                            this.xuanzhong=true//则选中
                        }else{
                            this.xuanzhong=false//否则为fasle
                        }
                    })
                    this.selectList.splice(index, 1)
                }
            }
            //删除选中人员，对应部门删除
            // this.treeObject = newList

        },
        //人员列表点击选中
        select(item, id) {
            var selectper = {}//先置空
            selectper = { deptId: id, isCheck: true, name: item.name, userId: item.userId, id: item.id }//每次点击选中的部门以及人员
            this.selectper = selectper//当前选中的人员
            this.selectList.push(selectper)
            var flag = true;
            for (let index = 0; index < this.renyuanList.length; index++) {
                const element = this.renyuanList[index];
                if(element.isCheck == false){//如果有一个为false
                    flag = false;//则为false
                }
            }
            if(flag){//如果全部选中
                this.xuanzhong=true//则选中
            }else{
                this.xuanzhong=false//否则为fasle
            } if (this.renyuanList[0].userList.length !== this.selectList.length) {
                this.xuanzhong=false
            }
            this.filterTransFer(this.selectList)
        },
        //需要过滤排查的数组
        filterTransFer(arr) {
            var obj = {};
            const newArr = arr.reduce(function (item, next) {
                obj[next.id] ? '' : obj[next.id] = true && item.push(next);
                return item;
            }, []);
            //更改人员列表选中未选中
            this.renyuanList.forEach(e => {
                e.userList.forEach(el => {
                    if (this.selectper.name == el.name) {//如果名字是一个则选中
                        el.isCheck = true
                    } else {
                        // el.isCheck = false
                    }
                })
            })
            this.selectList = newArr//筛选出来的人员
        },

    }
}
</script>
<style scoped  lang="less">
.title {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 20px;
}

.selectDiv {
    border: 1px solid #d9d9d9;
    width: 100%;
    padding: 0px 10px;
    word-wrap: break-word;
    border-radius: 4px;
    min-height: 32px;
}

.selectName {
    /* border: 1px solid #ccc; */
    padding: 2px 5px;
}

.close {
    margin-left: 2px;
}

.perpleSelect {
    width: 695px;
    height: 500px;
    padding: 0px 5px;
    overflow-y: scroll;
    border: 1px solid #ccc;
}

.bumen {
    color: #1890FF;
}

.selectpre {
    color: #1890FF;
}
</style>